﻿using Common;
using hhg.Video.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace hhg.Video.Controllers
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			return View();
		}

		 
		

		[DllImport("shell32.dll ")]
		public static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

		[HttpPost]
		public ActionResult Crawler(string key)
		{
			var config = ConfigHelper.GetCrawlerConfig();

			int n= ShellExecute(IntPtr.Zero, new StringBuilder("Open"), new StringBuilder(config.CrawlerExe), new StringBuilder(key), new StringBuilder(""), 1);

			return Json(n>0);
		}


		public JsonResult GetVideos(string url,string name)
		{
			var config = ConfigHelper.GetCrawlerConfig();


			var videos = new List<Models.VideoEntity>();
			var files = System.IO.Directory.GetFiles(config.VideosPath);

			if (!name.IsNullOrWhiteSpace())
			{
				var fileName = files.FirstOrDefault(s=>Path.GetFileNameWithoutExtension(s)==name );

				if (fileName != null)
				{
					var json = System.IO.File.ReadAllText(fileName);
					var tempVideos = json.DeserializeObject<List<Models.VideoEntity>>();
					videos.AddRange(tempVideos);

					
				}
			}
			foreach (var item in files)
			{
				var json = System.IO.File.ReadAllText(item);
				var tempVideos = json.DeserializeObject<List<Models.VideoEntity>>();
				videos.AddRange(tempVideos );
			}

			

			if (!url.IsNullOrWhiteSpace())
			{
				videos = videos.Where(s => s.PUrl == url).ToList(); ;
			}

			return Json(videos);
		}

		 
	}
}